package com.kob.backend.service.impl.user.account;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.User;
import com.kob.backend.service.user.account.InfoService;
import com.kob.backend.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author QiaoQi
 * @version 1.0
 */
@Service
public class InfoServiceImpl implements InfoService {

    @Value("${oss.endpoint}")
    private String ossEndpoint;

    @Value("${oss.accessKeyId}")
    private String ossAccessKeyId;

    @Value("${oss.accessKeySecret}")
    private String ossAccessKeySecret;

    @Value("${oss.bucketName}")
    private String ossBucketName;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, String> getinfo() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();

        Map<String, String> map = new HashMap<>();
        map.put("error_message", "success");
        map.put("id", user.getId().toString());
        map.put("username", user.getUsername());
        map.put("photo", user.getPhoto());
        return map;
    }

    @Override
    public Map<String, String> uploadAvatar(String avatarData, String userId) {
        // 处理上传到oss服务器的逻辑
        byte[] imageData = Base64.getDecoder().decode(avatarData);

        // 创建OSSClient对象
        OSS ossClient = new OSSClientBuilder().build(ossEndpoint, ossAccessKeyId, ossAccessKeySecret);

        try {
            // 生成文件名，可以使用用户ID或者其他唯一标识来命名文件
            String fileName = "avatar_" + userId + ".jpg";

            // 将字节数组上传到OSS服务器
            ossClient.putObject(ossBucketName, fileName, new ByteArrayInputStream(imageData));

            // 获取上传后的图片URL
            String imageUrl = "https://" + ossBucketName + "." + ossEndpoint + "/" + fileName;

            // 在数据库中修改用户头像信息
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", userId);
            User user = userMapper.selectOne(userQueryWrapper);
            user.setPhoto(imageUrl);
            userMapper.update(user, userQueryWrapper);

            // 构建返回结果
            Map<String, String> map = new HashMap<>();
            map.put("error_message", "success");
            map.put("imageUrl", imageUrl);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            // 处理上传失败的情况
            Map<String, String> errorMap = new HashMap<>();
            errorMap.put("error_message", "上传失败，请稍后重试");
            return errorMap;
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

    @Override
    public Map<String, String> updateUsername(String newUsername, String userId) {
        Map<String, String> map = new HashMap<>();
        String username = newUsername;
        if (username == null) {
            map.put("error_message", "昵称不能为空");
            return map;
        }

        username = username.trim(); // 去掉字符串首尾的空格
        if (username.length() == 0) {
            map.put("error_message", "昵称不能为空");
            return map;
        }


        if (username.length() > 10) {
            map.put("error_message", "昵称长度不能大于10");
            return map;
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        List<User> users = userMapper.selectList(userQueryWrapper);
        if (!users.isEmpty()) {
            map.put("error_message", "昵称已存在");
            return map;
        }

        QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
        userQueryWrapper2.eq("id", userId);
        User user = userMapper.selectOne(userQueryWrapper2);
        user.setUsername(username);
        userMapper.updateById(user);

        map.put("error_message", "success");
        return map;
    }
}
